package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.client.FastDFSClient;
import com.example.controller.vo.RequestLoginVo;
import com.example.controller.vo.ResponseUserVo;
import com.example.controller.vo.Result;
import com.example.entity.PageView;
import com.example.entity.User;
import com.example.service.IUserService;
import com.example.utils.JwtHelper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author yzy
 * @since 2025-08-04
 */
@RestController
@RequestMapping("/user")
@ConfigurationProperties(prefix = "custom")
@Data
public class UserController {

    @Autowired
    private IUserService iuserService;

    private String fastServer;

    //    添加消息前需要下拉框显示所有用户名
    @GetMapping("/selectUserName")
    public Result selectUserName() {
        List<User> user = iuserService.list();
        return Result.success(user);
    }
    //登录
    @PostMapping("/login")
    public Result login(@RequestBody RequestLoginVo requestLoginVo) {
        //验证 获取登录用户对象
        User user = iuserService.login(requestLoginVo);
        if (user == null) {
            return Result.failed("用户或密码错误");
        }
        // 生成token
        String token = JwtHelper.createToken(user.getId(), user.getUserName());
        return Result.success(token);
    }

    //按用户名查询用户
    @GetMapping("getByUserName")
    public Result getByUserName(@RequestParam("userName") String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userName);
        User user = iuserService.getOne(queryWrapper);
        if (user != null) {
            // 返回用户身份 1:用户 0：管理员
            ResponseUserVo responseUserVo = new ResponseUserVo();
            responseUserVo.setUserId(user.getId());
            responseUserVo.setUserName(user.getUserName());
            responseUserVo.setUserEmail(user.getUserEmail());
            responseUserVo.setUserAvatar(user.getUserAvatar());
            responseUserVo.setUserRole(user.getUserRole());
            return Result.success(responseUserVo);
        }
        return Result.failed();
    }

    // 注册功能
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        user.setUserAvatar(null);
        user.setUserRole(1);
        user.setIsLogin(false);
        user.setIsWord(false);
        user.setCreateTime(LocalDateTime.now());
        iuserService.save(user);
        return Result.success(null);
    }

    // 分页查询+模糊查询用户列表
    @GetMapping("/list")
    public Result list(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize,
                       @RequestParam(value = "isWord", required = false) Boolean isWord,
                       @RequestParam(value = "userAccount", required = false) String userAccount) {
        // 创建分页对象
        Page<User> page = new Page<>(pageNum, pageSize);
        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 模糊查询：如果userAccount不为空，则添加模糊匹配条件
        if (StringUtils.hasText(userAccount)) {
            queryWrapper.like("user_account", userAccount);
        }
        if (isWord != null) {
            queryWrapper.eq("is_word", isWord);
        }

        // 执行分页查询
        Page<User> userPage = iuserService.page(page, queryWrapper);
        // 封装返回结果
        PageView pageView = new PageView();
        pageView.setPageNum(Integer.parseInt(page.getCurrent() + ""));
        pageView.setPageSize(Integer.parseInt(page.getSize() + ""));
        pageView.setTotalPage(page.getPages());
        pageView.setAllRow(page.getTotal());
        pageView.setData(page.getRecords());
        return Result.success(pageView);
    }

    // 新增用户信息
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        // 获取前端传入的用户名
        String userAccount = user.getUserAccount();
        // 查询数据库中是否已存在此用户
        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        // 执行查询（存在返回1，不存在返回0）
        long count = iuserService.count(queryWrapper);
        // 判断是否存在。count>0 表示已存在
        if (count == 0) {
            // 不存在 执行新增操作
            // 默认用户可登录
            user.setIsLogin(false);
            user.setCreateTime(LocalDateTime.now());
            iuserService.save(user);
            return Result.success("新增用户成功");
        } else {
            //已存在，返回失败信息
            return Result.failed("该用户已存在，新增失败");
        }
    }

    // 修改用户信息
    @PutMapping("/update")
    public Result update(@RequestBody User user) {

        // 检查数据库中是否存在此用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account",user.getUserAccount());
        User existUser = iuserService.getOne(queryWrapper);
        if(existUser==null){
            return Result.failed("该用户不存在，无法修改");
        }
        user.setId(existUser.getId());
        // 执行更新操作
        boolean isUpdate = iuserService.updateById(user);
        // 根据跟新结果返回响应
        if (isUpdate) {
            return Result.success("用户信息修改成功");
        } else {
            return Result.failed("用户信息修改失败，请检查数据是否有变化");
        }
    }

    //删除用户信息
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id) {
        iuserService.removeById(id);
        return Result.success("删除用户成功");
    }

    //按id查询当前用户信息git
    @GetMapping("{id}")
    public Result get(@PathVariable("id") Integer id) {
        User user = iuserService.getById(id);
        user.setUserPwd(null);
        return Result.success(user);
    }

    //头像上传
    @PostMapping("/upload")
    public Result uploadImage(MultipartFile image){
        String fileName = image.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        FastDFSClient fastDFSClient = null;
        try {
            fastDFSClient = new FastDFSClient("fdfs_client.conf");
            String fileId = fastDFSClient.uploadFile(image.getBytes(), suffix);
            String newFileName = fastServer + fileId;
            //log.info("文件上传的地址为:{}",newFileName);
            return Result.success(newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
